//
//  GuanzhuViewController.m
//  YeDian
//
//  Created by 罗西 on 3/26/16.
//  Copyright © 2016 罗西. All rights reserved.
//

#import "GuanzhuViewController.h"
#import "Tools.h"
#import "ConfigData.h"
#import "ASIFormDataRequest.h"
#import "AppDelegate.h"
#import "MBProgressHUD.h"
#import "Toast+UIView.h"
#import "JSON.h"
#import "MyFansTableViewCell.h"
#import "UIButton+WebCache.h"
#import "MJRefresh.h"
#import "ziliaoViewController.h"

@interface GuanzhuViewController ()<UITableViewDataSource,UITableViewDelegate>{
    NSDictionary *myInfoDic;
    NSInteger currentPage;
}

@property (nonatomic,strong) UITableView *mainTableView;
@property (nonatomic,strong) NSMutableArray *itemsArray;
@property (nonatomic,strong) UISegmentedControl *control;

@end

@implementation GuanzhuViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    CGRect frame_img= CGRectMake(0,(44-19)/2,19,19);
    UIImageView* backView=[[UIImageView alloc] initWithFrame:frame_img];
    backView.image=[UIImage imageNamed:@"back2016"];
    CGRect frameBtn= CGRectMake(0, 0,50, 44);
    UIButton* homeBtn= [[UIButton alloc] initWithFrame:frameBtn];
    [homeBtn addTarget:self action:@selector(backFn) forControlEvents:UIControlEventTouchUpInside];
    [homeBtn addSubview:backView];
    UIBarButtonItem* barHomeBtn= [[UIBarButtonItem alloc] initWithCustomView:homeBtn];
    self.navigationItem.leftBarButtonItem=barHomeBtn;
    
    self.title = @"关注";
    
    [self loadUI];
}

-(void)backFn{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)loadUI{
    _control = [[UISegmentedControl alloc]initWithItems:@[@"夜店",@"人"]];
    _control.frame = CGRectMake(0, 0, SCREEN_WIDTH, 30);
    _control.tintColor = [UIColor redColor];
    _control.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_control];
    _control.selectedSegmentIndex = 0;
    [_control addTarget:self action:@selector(controllerPressed:) forControlEvents:UIControlEventValueChanged];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.mainTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 30, SCREEN_WIDTH, SCREEN_HEIGHT-64-30)];
    [self.view addSubview:self.mainTableView];
    [self.mainTableView setDataSource:self];
    [self.mainTableView setDelegate:self];
    [self.mainTableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [self.mainTableView setBackgroundColor:[UIColor colorWithRed:252/255.0 green:252/255.0 blue:252/255.0 alpha:1.0]];
    //[self.mainTableView launchRefreshing];
    
    self.mainTableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        currentPage = 0;
        [self loadData];
    }];
    
    self.mainTableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        currentPage++;
        [self loadData];
    }];

    currentPage = 0;
    _itemsArray = [NSMutableArray new];
    
    [self loadData];
    
}

- (void) controllerPressed:(UISegmentedControl*)sender {
    currentPage = 0;
    _itemsArray = [NSMutableArray new];
    [self loadData];
    
    /* 添加代码,处理值的变化 */
}

-(void)loadData{
    NSUserDefaults*  ud=[[NSUserDefaults alloc] init];
    NSUserDefaults *accountDefaults = [NSUserDefaults standardUserDefaults];
    NSString* mp_ = [accountDefaults objectForKey:@"phone"];
    //NSString* mp_=[ud objectForKey:@"mp"];
    if (!mp_) {
        return;
    }
    NSLog(@"mp:%@",mp_);
    NSString* loginURL=HOST;
    if (_control.selectedSegmentIndex == 0) {
        loginURL=[loginURL stringByAppendingString:@"/index.php/appAttention/findAttentionMerchantList"];
        
    }else{
        loginURL=[loginURL stringByAppendingString:@"/index.php/appAttention/findAttentionUserList"];
    }
    
    
    NSURL* url=[[NSURL alloc] initWithString:loginURL];
    ASIFormDataRequest *req=[ASIFormDataRequest requestWithURL:url];
    
    [req addPostValue:[accountDefaults objectForKey:@"uid"] forKey:@"uid"];
    [req addPostValue:[NSString stringWithFormat:@"%ld",currentPage] forKey:@"currentPage"];
    
    [req startSynchronous];
    NSError *error = [req error];
    NSLog(@"保存URL.loginURL==%@",req.url);
    
    if (!error) {
        AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
        [MBProgressHUD hideHUDForView:app.window animated:YES];
        
        NSString *response = [req responseString];
        NSLog(@"保存返回结果%@",response);
        myInfoDic=[response JSONValue];
        NSString* uid=[myInfoDic objectForKey:@"uid"];
        NSLog(@"ID%@",uid);
        
        if (currentPage == 0) {
            _itemsArray = [NSMutableArray new];
        }
        
        [_itemsArray addObjectsFromArray:[myInfoDic objectForKey:@"list"]];
        [self.mainTableView.header endRefreshing];
        [self.mainTableView.footer endRefreshing];
        [self.mainTableView reloadData];
        //[self performSelectorOnMainThread:@selector(finishLoadMyInfoFn) withObject:nil waitUntilDone:YES];
    }else{
        [self.mainTableView.header endRefreshing];
        [self.mainTableView.footer endRefreshing];
        NSLog(@"move failed:%@", [error localizedDescription]);
    }
}



#pragma mark UITableViewDelegate/UITableViewDataSource

/**
 *  每个cell有多少行
 */
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 1;
}


/**
 *  有多少个section
 */
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return _itemsArray.count;
}

/**
 *  section的title
 */
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    
    return nil;
}

/**
 *  header的距离
 */
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return CGFLOAT_MIN;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 10;
}

/**
 *  row的高度
 */
-(CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 80;
}

/**
 *  cell的属性
 */
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    MyFansTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    
    if (cell == nil) {
        cell = [[MyFansTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    
    NSDictionary* dic = [_itemsArray objectAtIndex:indexPath.section];
    NSString *str_logo = [dic objectForKey:@"logo"];
    NSString *str_name = [dic objectForKey:@"name"];
    NSString *str_desc = [dic objectForKey:@"desc"];
    if ([str_logo isEqual:[NSNull null]]) {
        str_logo = @"";
    }
    if ([str_name isEqual:[NSNull null]]) {
        str_name = @"";
    }
    if ([str_desc isEqual:[NSNull null]]) {
        str_desc = @"";
    }
    [cell.imgView setImageWithURL:[NSURL URLWithString:str_logo] forState:UIControlStateNormal];
    cell.nameLabel.text = str_name;
    cell.desLabel.text = str_desc;
;
    
    return cell;
}

/**
 *  点击事件
 */
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSDictionary* dic = [_itemsArray objectAtIndex:indexPath.section];
    ziliaoViewController *vc = [ziliaoViewController new];
    vc.pID = [dic objectForKey:@"target_merchantid"];
    [self.navigationController pushViewController:vc animated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
